package com.hengtian.roastwall.service.impl;

import com.hengtian.roastwall.entity.LoginUser;
import com.hengtian.roastwall.entity.User;
import com.hengtian.roastwall.mapper.UserMapper;
import com.hengtian.roastwall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        // 获取用户信息
        User user = userMapper.getUserInfo(userName);
        System.out.println("自定义获取登录信息");
        // 查询不到该用户
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户名或密码错误");
        }
        // 获取用户权限, 从数据库中获取
//        List<String> list = new ArrayList<>(Arrays.asList("test", "admin"));
        List<String> authorities = userService.getAuthorities(user);


        // 查询到了用户，将用户封装进UserDetails对象中
        return new LoginUser(user, authorities);
    }
}
